﻿package net.wangit.view.unit.component;

import net.wangit.MapList;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.framework.config.BeanFactory;
import net.wangit.framework.session.AgileSession;
import net.wangit.framework.session.UnitSettings;
import net.wangit.support.PageNavigator;
import net.wangit.view.unit.grid.Grid;
import net.wangit.view.unit.grid.ListGrid;

public class ListUnitWriter extends FormUnitWriter {

	public ListUnitWriter() {
	}

	protected Grid getGrid(ActionContext ac) {
		return new ListGrid(ac, fu);
	}

	protected void setNavigator(ActionContext ac) {
		int listSize = fu.getListSize();
		if (listSize > 0)
			attributes.put("navigator", getNavigatorHtml(ac));
	}

	private String getNavigatorHtml(ActionContext ac) {
		AgileSession session = ActionContextHelper.getSession(ac);
		UnitSettings us = session.getUnitSettings(fu.getDomain(), fu.getId());
		int dataSize = 0;
		MapList data = fu.getData();
		if (data != null)
			dataSize = data.size();
		int maxSize = us.getMaxSize();
		if (maxSize <= 0)
			maxSize = dataSize;
		int pageNumber = us.getPageNumber();
		if (pageNumber <= 0 && dataSize > 0)
			pageNumber = 1;
		int maxPageNumber = (int) Math.ceil(((double) maxSize * 1.0D)
				/ (double) fu.getListSize());
		PageNavigator navigator = BeanFactory.getNavigator(fu.getNavigator());
		return navigator.getHtml(fu.getDomain(), fu.getId(), dataSize, maxSize,
				fu.getListSize(), pageNumber, maxPageNumber);
	}
}
